package com.zhangck.bos2_0.Service.take_delivery.Impl;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.CommonTermsQueryBuilder.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StreamUtils;

import com.zhangck.bos2_0.Service.take_delivery.WayBillquickServices;
import com.zhangck.bos2_0.dao.WayBillQuickRepoistory;
import com.zhangck.bos2_0.index.indexRepository;

import cn.itcast.bos.domain.take_delivery.WayBill;

/** 
* @author 上午茶
* @version 创建时间：2018年6月12日 下午10:46:37 
* 类说明 
*/
@Service
@Transactional
public class WayBillquickServicesImpl implements WayBillquickServices {

	@Autowired
	private WayBillQuickRepoistory wayBillRepoistory;
	
	@Autowired
	private indexRepository indexRepository;
	
	
	@Autowired
	private ElasticsearchTemplate elasticsearchTemplate;
	
	@Autowired
	private Client client;
	
	@Override
	public void save(WayBill model) {
		WayBill wayBillNum = wayBillRepoistory.findByWayBillNum(model.getWayBillNum());
		System.out.println(model.getWayBillNum()+"aaa3333333");
		if (wayBillNum==null) {
			System.out.println("不存在");
			wayBillRepoistory.save(model);
			indexRepository.save(model);
		}else {
			try {
				wayBillRepoistory.delete(wayBillNum.getId());
				wayBillRepoistory.save(model);
			
				SearchResponse searchResponse = client.prepareSearch("bos_waybill")
						.setTypes("wayBill").setQuery(QueryBuilders.termQuery("order.id",model.getOrder().getId())).get();
					SearchHits hits = searchResponse.getHits();
					System.out.println(model.getOrder().getId()+"asssddddddd");
					Iterator<SearchHit> iterator = hits.iterator();
					model.setSendName("<em class='highlight'>"+model.getSendName()+"</em>");
					model.setRecName("<em class='highlight'>"+model.getRecName()+"</em>");
					if (hits.getTotalHits()!=0) {
						if (iterator.hasNext()) {
						//System.out.println(iterator.next().getSource().get("id")+"aaaaaaaaa");
						Integer id = (Integer) (iterator.next().getSource().get("id"));
						indexRepository.delete(id);
						System.out.println("刪除成功");
						indexRepository.save(model);
						System.out.println("index保存成功");
						}
			}else if (hits.getTotalHits()==0) {
				indexRepository.save(model);
			}	
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Page<WayBill> pageData(WayBill wayBill,Pageable request) {
		System.out.println(wayBill.getWayBillNum()+"aaaaaa");
		if (StringUtils.isBlank(wayBill.getWayBillNum())
			&&StringUtils.isBlank(wayBill.getSendAddress())
			&&StringUtils.isBlank(wayBill.getRecAddress())
			&&StringUtils.isBlank(wayBill.getSendProNum())
			&&(wayBill.getSignStatus()==null||wayBill.getSignStatus()==0)) {
			return indexRepository.findAll(request);
		}
		else {
			BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
			if (StringUtils.isNotBlank(wayBill.getWayBillNum())) {
				TermQueryBuilder builders = new TermQueryBuilder("wayBillNum", wayBill.getWayBillNum());
				queryBuilder.must(builders);
			}
			if (StringUtils.isNotBlank(wayBill.getSendAddress())) {
				WildcardQueryBuilder builders = new WildcardQueryBuilder("sendAddress","*"+wayBill.getSendAddress()+"*");
			
				QueryStringQueryBuilder stringQueryBuilder = 
						new QueryStringQueryBuilder(wayBill.getSendAddress()).field("sendAddress").analyzeWildcard(true);
				
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(builders);
				boolQueryBuilder.should(stringQueryBuilder);
				
				queryBuilder.must(boolQueryBuilder);
			}
			if (StringUtils.isNotBlank(wayBill.getRecAddress())) {
				WildcardQueryBuilder builders = new WildcardQueryBuilder("recAddress","*"+wayBill.getRecAddress()+"*");
				queryBuilder.must(builders);
				
				QueryStringQueryBuilder stringQueryBuilder = new QueryStringQueryBuilder(wayBill.getRecAddress())
						.field("recAddress").analyzeWildcard(true);
				
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(builders);
				boolQueryBuilder.should(stringQueryBuilder);
				
				queryBuilder.must(boolQueryBuilder);
			}
			if (StringUtils.isNoneBlank(wayBill.getSendProNum())) {
				TermQueryBuilder builder = new TermQueryBuilder("sendProNum", wayBill.getSendProNum());
				queryBuilder.must(builder);
			}
			if (wayBill.getSignStatus()!=null&&wayBill.getSignStatus()!=0) {
				TermQueryBuilder builder = new TermQueryBuilder("signStatus", wayBill.getSignStatus());
				queryBuilder.must(builder);
			}
			SearchQuery searchQuery = new NativeSearchQuery(queryBuilder);
			searchQuery.setPageable(request);
			return indexRepository.search(searchQuery);
		}
	}

	@Override
	public WayBill findWayBillNum(String wayBillNum) {
		return wayBillRepoistory.findByWayBillNum(wayBillNum);
	}

	@Override
	public List<WayBill> findWayBills(WayBill wayBill) {
		if (StringUtils.isBlank(wayBill.getWayBillNum())
				&& StringUtils.isBlank(wayBill.getSendAddress())
		// 判断WayBill 中条件是否存在
				&& StringUtils.isBlank(wayBill.getRecAddress())
				&& StringUtils.isBlank(wayBill.getSendProNum())
				&& (wayBill.getSignStatus() == null || wayBill.getSignStatus() == 0)) {
			// 无条件查询 、查询数据库
			return wayBillRepoistory.findAll();
		} else {
			// 查询条件
			// must 条件必须成立 and
			// must not 条件必须不成立 not
			// should 条件可以成立 or
			BoolQueryBuilder query = new BoolQueryBuilder(); // 布尔查询 ，多条件组合查询
			// 向组合查询对象添加条件
			if (StringUtils.isNoneBlank(wayBill.getWayBillNum())) {
				// 运单号查询
				QueryBuilder tempQuery = new TermQueryBuilder("wayBillNum",
						wayBill.getWayBillNum());
				query.must(tempQuery);
			}
			if (StringUtils.isNoneBlank(wayBill.getSendAddress())) {
				// 发货地 模糊查询
				// 情况一： 输入"北" 是查询词条一部分， 使用模糊匹配词条查询
				QueryBuilder wildcardQuery = new WildcardQueryBuilder(
						"sendAddress", "*" + wayBill.getSendAddress() + "*");

				// 情况二： 输入"北京市海淀区" 是多个词条组合，进行分词后 每个词条匹配查询
			/*	QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(
						wayBill.getSendAddress()).field("sendAddress")
						.defaultOperator(org.apache.lucene.queryparser.classic.QueryParser.Operator.AND);*/
						

				// 两种情况取or关系
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(wildcardQuery);
				//boolQueryBuilder.should(queryStringQueryBuilder);

				query.must(boolQueryBuilder);
			}
			if (StringUtils.isNoneBlank(wayBill.getRecAddress())) {
				// 收货地 模糊查询
				QueryBuilder wildcardQuery = new WildcardQueryBuilder(
						"recAddress", "*" + wayBill.getRecAddress() + "*");
				query.must(wildcardQuery);
			}
			if (StringUtils.isNoneBlank(wayBill.getSendProNum())) {
				// 速运类型 等值查询
				QueryBuilder termQuery = new TermQueryBuilder("sendProNum",
						wayBill.getSendProNum());
				query.must(termQuery);
			}
			if (StringUtils.isNoneBlank(wayBill.getSendProNum())) {
				// 速运类型 等值查询
				QueryBuilder termQuery = new TermQueryBuilder("sendProNum",
						wayBill.getSendProNum());
				query.must(termQuery);
			}
			if (wayBill.getSignStatus() != null && wayBill.getSignStatus() != 0) {
				// 签收状态查询
				QueryBuilder termQuery = new TermQueryBuilder("signStatus",
						wayBill.getSignStatus());
				query.must(termQuery);
			}

			SearchQuery searchQuery = new NativeSearchQuery(query);
			// ElasticSearch 允许搜索分页查询，最大数据条数10000
			Pageable pageable = new PageRequest(0, 10000);
			searchQuery.setPageable(pageable); // 分页效果

			// 有条件查询 、查询索引库
			return indexRepository.search(searchQuery).getContent();
		}
	}

	
}
